import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as authApi from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = ref(null) // Token由Cookie管理，不需要存储在localStorage

  const isLoggedIn = computed(() => !!user.value)

  /**
   * 登录
   * @param {object} credentials - 登录凭证 { username, password }
   */
  const login = async (credentials) => {
    const response = await authApi.login(credentials)
    // Token已经存储在HttpOnly Cookie中
    user.value = response.data.user
    token.value = response.data.token // 保存一份用于显示，实际认证使用Cookie
    localStorage.setItem('user', JSON.stringify(response.data.user))
    return response
  }

  /**
   * 登出
   */
  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('Logout API error:', error)
    } finally {
      // 无论API是否成功，都清除本地状态
      user.value = null
      token.value = null
      localStorage.removeItem('user')
    }
  }

  // 初始化用户信息
  const initUser = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      try {
        user.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('Failed to parse saved user:', error)
        localStorage.removeItem('user')
      }
    }
  }

  initUser()

  return {
    user,
    token,
    isLoggedIn,
    login,
    logout
  }
})

